package com.conf.web;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.constant.ScenicConstant;
import com.exception.ServiceException;
import com.util.DateUtils;
import com.util.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.ui.Model;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.*;

@RestController
@RequestMapping("/file")
@Slf4j
public class FileUpload {

    /**
     * 批量上传文件，返回文件的相对路径 路径用 && 拼接
     * @param files
     * @param request
     * @return
     */
    @PostMapping(value = "/upload")
    public R uploadTicketImage(@PathVariable("file") MultipartFile[] files, HttpServletRequest request) {
        //quill-editor 上传图片
        if(files.length==0) {
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
            files = fileMap.values().toArray(new MultipartFile[fileMap.size()]);
        }
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < files.length; i++) {
            MultipartFile file = files[i];
            try {
                if (file == null) {
                    throw new ServiceException("上传文件为空");
                }

                String fileName = file.getOriginalFilename();
                if (StringUtils.isBlank(fileName)) {
                    throw new ServiceException("上传文件为空");
                }

                String[] names = fileName.split("\\.");
                String suffix = names[names.length - 1];
                if (ScenicConstant.allowSuffix.indexOf(suffix) == -1) {
                    throw new ServiceException(String.format("上传失败，不支持的文件格式:%s,支持的格式:%s",suffix,ScenicConstant.allowSuffix));
                }

                if (file.getSize() > ScenicConstant.maxSize) {
                    throw new ServiceException(String.format("上传失败，文件上传不能大于:%sM",ScenicConstant.maxSize/1024/1024));
                }

                //路径以 year/month 分类
                String path = request.getSession().getServletContext().getRealPath("/");
                Calendar calendar = Calendar.getInstance();
                int year = calendar.get(Calendar.YEAR);

                int month = calendar.get(Calendar.MONTH)+1;
                String relativePath = "";
                //文档格式的路径
                if(ScenicConstant.docSuffix.indexOf(suffix) != -1){
                    relativePath = String.format("files/doc%s/%s",year,month);
                }
                //图片格式的路径
                if(ScenicConstant.picSuffix.indexOf(suffix) != -1){
                    relativePath = String.format("files/image/%s/%s",year,month);
                }
                path += relativePath;
                File f = new File(path);
                if(!f.exists()){
                    f.mkdirs();
                }
                //文件名
                String name = names[0];
                name += String.format("(%s).%s",new Random().nextInt(),suffix);
                 f = new File(path, name);
                 //上传
                file.transferTo(f);
                //相对路径+文件名
                if(i != 0){
                    builder.append("&&");
                }
                builder.append(relativePath+"/"+name);
            } catch (Exception e) {
                e.printStackTrace();
                throw new ServiceException(e.getMessage());
            }
        }
        return R.ok(builder.toString());
    }

}
